from django.http import HttpResponse, JsonResponse, FileResponse
from django.views.decorators.http import require_http_methods
from .models import Firmware
import json

from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
@require_http_methods(["POST"])
def fw_interface(request):
    try:
        data = json.loads(request.body)
        action = data.get("action")

        if action == "show_available_fw":
            available_fw = Firmware.objects.filter(is_active=True)
            return JsonResponse({
                "status": "success",
                "available_fw": [fw.version for fw in available_fw]
            })

        elif action == "transmit_fw":
            version_need = data.get("version")
            print(version_need)

            try:

                fw = Firmware.objects.get(version=version_need, is_active=True)

                # 使用流式响应（避免内存问题）

                response = FileResponse(

                    open(fw.file.path, 'rb'),

                    content_type='application/json-seq',

                    as_attachment=True,

                    filename=fw.file.name.split("/")[-1]

                )

                response['X-Firmware-Version'] = fw.version

                return response

            except Firmware.DoesNotExist:
                return JsonResponse({
                    "status": "error",
                    "message": "固件不存在或不可用"
                }, status=404)

        else:
            return JsonResponse({
                "status": "error",
                "message": "无效操作"
            }, status=400)

    except json.JSONDecodeError:
        return JsonResponse({
            "status": "error",
            "message": "非法JSON格式"
        }, status=400)
    except Exception as e:
        return JsonResponse({
            "status": "error",
            "message": f"服务器错误: {str(e)}"
        }, status=500)
